﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using olierFrm.DataBase.FrameWork.Plugin;
using System.Data;
using olierFrm.DataBase.FrameWork.DataDictornary;
using olierFrm.GeneralCache;

namespace olierFrm.DataBase.FrameWork.DataObject
{
    /// <summary>
    /// 
    /// </summary>
    public class DataObjectSQL : DefinedSQL
    {
        public class DataObjectField
        {
            public string SqlID { get; set; }
            public string Idx { get; set; }
            public string Field { get; set; }
            public bool Hide { get; set; }
            public string BaseID { get; set; }
            public bool Display { get; set; }
            public string DefaultValue { get; set; }
            public string LableText { get; set; }
            public string Memo { get; set; }
            public string Type { get; set; }
            public string ValidatorRegex { get; set; }
            public string SQL { get; set; }
        }

        public WF_DataObject DataObject
        {
            get;
            private set;
        }


        public List<WF_DataObjectSQL> DataObjectSQLs
        {
            get;
            private set;
        }



        public List<WF_DataObjectParams> DataObjectParams
        {
            get;
            private set;
        }

        public List<DataObjectField> DataObjectFields
        {
            get;
            private set;
        }

        public const string DataObjectCachePrefix = "DataObject=";
        public const string DataObjectParamCachePrefix = "DataObjectParam=";
        public const string DataObjectSQLCachePrefix = "DataObjectSQL=";

        public DataObjectSQL(string SqlID)
        {
            this.SqlID = SqlID;
            string CacheKey = DataObjectCachePrefix + SqlID;
            if (!Cache.KeyExists(CacheKey))
            {
                var dataobject = (from d in this.DBEntity.WF_DataObject where d.ObjectName == SqlID select d).ToList();
                if (!dataobject.Any())
                    throw new FrameWorkError() { SqlID = this.SqlID, ErrorObject = "DataObject", ErrorType = "执行查询时", Summary = "DataObject：" + SqlID + "，没有定义！" };
                DataObject = dataobject.First();
                Cache.Add(CacheKey, DataObject);
            }
            else
                DataObject = (WF_DataObject)Cache.Get(CacheKey);

            string CacheSQLKey = DataObjectSQLCachePrefix + SqlID;
            if (!Cache.KeyExists(CacheSQLKey))
            {
                DataObjectSQLs = (from d in this.DBEntity.WF_DataObjectSQL where d.ObjectName == SqlID orderby d.Idx select d).ToList();

                Cache.Add(CacheSQLKey, DataObjectSQLs);

            }
            else
                DataObjectSQLs = (List<WF_DataObjectSQL>)Cache.Get(CacheSQLKey);

            //if (DataObjectSQLs != null)
            foreach (var d in DataObjectSQLs)
            {
                this.ObjectSQL.Add(new ObjectSQL() { Idx = d.Idx, SqlID = d.ObjectName, SQLText = d.SQL });
            }

            //var dataobjectfield = from d in this.DBContext.WF_DataObjectField
            //                      where d.SqlID == SqlID
            //                      orderby d.Idx
            //                      join bf in this.DBContext.t_frm_BaseField
            //                       on d.BaseID equals bf.BaseID into x
            //                      from y in x.DefaultIfEmpty()
            //                      select new DataObjectField
            //                      {
            //                          SqlID = d.SqlID,
            //                          Idx = d.Idx,
            //                          Hide = d.Hide,
            //                          Field = d.Field,
            //                          BaseID = d.BaseID,
            //                          Display = d.Display,
            //                          DefaultValue = y.DefaultValue,
            //                          LableText = y.LableText == null ? d.LableText : y.LableText,
            //                          Memo = y.Memo,
            //                          SQL = y.SQL,
            //                          Type = y.Type,
            //                          ValidatorRegex = y.ValidatorRegex
            //                      };


            string CacheParamKey = DataObjectParamCachePrefix + SqlID;
            if (!Cache.KeyExists(CacheParamKey))
            {
                DataObjectParams = (from d in this.DBEntity.WF_DataObjectParams where d.ObjectName == SqlID select d).ToList();

                Cache.Add(CacheParamKey, DataObjectParams.ToList());

            }
            else
                DataObjectParams = (List<WF_DataObjectParams>)Cache.Get(CacheParamKey);

            //if (DataObjectParams != null)
            foreach (var s in DataObjectParams)
            {
                this.ObjectSQLParam.Add(new ObjectSQLParam() { ParamName = s.ParamName, ParamType = s.ParamType });
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public DataSet ExecuteSQL()
        {
            DataSet ds = new DataSet(SqlID);
            try
            {
                for (int i = 0; i < this.ObjectSQL.Count; i++)
                {
                    DataTable dt = SqlHelper.ExecuteQuery(this.ObjectSQL[i].SQLText, this.ObjectSQLParam, (SqlID + "_" + i));
                    ds.Tables.Add(dt);

                }
            }
            catch (Exception ex)
            {
                throw new FrameWorkError()
                {
                    SqlID = this.SqlID,
                    ErrorObject = "DataObject",
                    ErrorType = "执行查询时",
                    Summary = "DataObject：" + SqlID + "，" + ex.Message
                };
            }
            finally
            {
                this.Dispose();
            }
            //for (int i = 0; i < ds.Tables.Count; i++)
            //{
            //    DataDictionary.BindCaptionToDataTable(ds.Tables[i]);
            //}
            return ds;
        }

        //public List<List<T>> ExecuteSQL<T>() where T : class ,new()
        //{
        //    List<List<T>> listModel = new List<List<T>>();
        //    foreach (var os in this.ObjectSQL)
        //    {
        //        listModel.Add(this.SqlHelper.ExecuteQuery<T>(os.SQLText, this.ObjectSQLParam));
        //    }
        //    return listModel;
        //}
    }
}
